{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3. 提示词模板之PromptTemplate\n",
    "方法1：使用构造方法来获取实例\n",
    "举例1：定义单一变量模板"
   ],
   "id": "3143db94ecef9697"
  },
  {
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-10-22T01:26:07.720522Z",
     "start_time": "2025-10-22T01:26:07.698392Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "# 定义变量模板\n",
    "prompt_template_ = PromptTemplate(\n",
    "    input_variables=[\"name\", \"todo\"],\n",
    "    template=\"你好。我的名字是{name}，我是一名{todo}.\",\n",
    ")\n",
    "# 使用模板生成提示词\n",
    "prompt1 = prompt_template_.format(name=\"Kai\", todo=\"程序员\")\n",
    "prompt2 = prompt_template_.format(name=\"CC\", todo=\"开发攻城狮\")\n",
    "print(prompt1)\n",
    "print(prompt2)"
   ],
   "id": "557f593b98cae05f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好。我的名字是Kai，我是一名程序员.\n",
      "你好。我的名字是CC，我是一名开发攻城狮.\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：定义多变量模板",
   "id": "d253b2b905ab08c5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T01:23:18.169859Z",
     "start_time": "2025-10-22T01:23:18.153327Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "# 定义多变量模板\n",
    "prompt_template = PromptTemplate(\n",
    "    template=\"请评价{brand}的优缺点，包括{aspect1}和{aspect2}.\",\n",
    "    input_variables=[\"brand\", \"aspect1\", \"aspect2\"],\n",
    ")\n",
    "# 使用模板生成提示词\n",
    "prompt1 = prompt_template.format(brand=\"Apple\", aspect1=\"价格\", aspect2=\"性能\")\n",
    "prompt2 = prompt_template.format(brand=\"Xiaomi\", aspect1=\"营销手段\", aspect2=\"电池续航\")\n",
    "print(prompt1)\n",
    "print(prompt2)"
   ],
   "id": "ebf0cf41951398a6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价Apple的优缺点，包括价格和性能.\n",
      "请评价Xiaomi的优缺点，包括营销手段和电池续航.\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方法2：使用from_template方法 (强烈推荐!!)",
   "id": "9ba3eae7fa0b9303"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T01:36:03.721863Z",
     "start_time": "2025-10-22T01:36:03.699793Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "# 定义变量模板\n",
    "prompt_template_ = PromptTemplate.from_template(template=\"你好。我的名字是{name}，我是一名{todo}.\")\n",
    "# 使用模板生成提示词\n",
    "prompt1 = prompt_template_.format(name=\"小智\", todo=\"人工智能助手\")\n",
    "print(prompt1)"
   ],
   "id": "e52cbdbfb105239d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好。我的名字是小智，我是一名人工智能助手.\n"
     ]
    }
   ],
   "execution_count": 34
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T01:35:21.006573Z",
     "start_time": "2025-10-22T01:35:20.992925Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "# 定义多变量模板\n",
    "prompt_template = PromptTemplate.from_template(template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "# 使用模板生成提示词\n",
    "prompt1 = prompt_template.format(product=\"手机\", aspect1=\"续航表现\", aspect2=\"性能释放\")\n",
    "print(prompt1)"
   ],
   "id": "993722f6a5d8111a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价手机的优缺点，包括续航表现和性能释放。\n"
     ]
    }
   ],
   "execution_count": 33
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "如果提示词模版不包含变量，则调用format()时，不要需要传入参数",
   "id": "6be942f8e9f23543"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T01:41:20.827754Z",
     "start_time": "2025-10-22T01:41:20.809215Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "TExt = \"请评价手机的优缺点，包括续航表现和性能释放。\"\n",
    "# 定义无变量模板\n",
    "prompt_template = PromptTemplate.from_template(TExt)\n",
    "# 使用模板生成提示词\n",
    "prompt1 = prompt_template.format()\n",
    "print(prompt1)"
   ],
   "id": "cb17891cae1dce8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价手机的优缺点，包括续航表现和性能释放。\n"
     ]
    }
   ],
   "execution_count": 35
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3.3部分提示词\n",
    "方法1：使用构造方法来获取实例"
   ],
   "id": "6f59c4d553862e25"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T03:05:28.397781Z",
     "start_time": "2025-10-22T03:05:28.367106Z"
    }
   },
   "cell_type": "code",
   "source": [
    "template = PromptTemplate(\n",
    "    template=\"你好。我的名字是{name}，我是一名{todo}.\",\n",
    "    input_variables=[\"name\", \"todo\"],\n",
    "    partial_variables={\"todo\": \"程序员\"}\n",
    ")\n",
    "prompt1 = template.format(name=\"小智\")\n",
    "print(\"提示词1：\", prompt1)"
   ],
   "id": "d0bbbd3bd18011ba",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词： 你好。我的名字是小智，我是一名程序员.\n"
     ]
    }
   ],
   "execution_count": 36
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方法2. 使用from_template方法",
   "id": "6f58d1163b064887"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T03:09:49.690862Z",
     "start_time": "2025-10-22T03:09:49.625351Z"
    }
   },
   "cell_type": "code",
   "source": [
    "template = PromptTemplate.from_template(\n",
    "    template=\"你好。我的名字是{name}，我是一名{todo}.\",\n",
    "    partial_variables={\"todo\": \"AI软件开发者\"}\n",
    ")\n",
    "prompt1 = template.format(name=\"AK\")\n",
    "print(\"提示词1：\", prompt1)"
   ],
   "id": "33c03f23b6e5f3ef",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1： 你好。我的名字是AK，我是一名AI软件开发者.\n"
     ]
    }
   ],
   "execution_count": 43
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方式3：组合提示词（了解）",
   "id": "e95c32d251ec5682"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T03:38:57.049749Z",
     "start_time": "2025-10-22T03:38:57.028786Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "template = (\n",
    "        PromptTemplate.from_template(\"Tell me a joke about {topic}\")\n",
    "        + \", make it funny\"\n",
    "        + \"\\n\\nand in {language}\"\n",
    ")\n",
    "prompt = template.format(topic=\"sports\", language=\"english\")\n",
    "print(prompt)"
   ],
   "id": "c8ead141dcc752bf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tell me a joke about sports, make it funny\n",
      "\n",
      "and in english\n"
     ]
    }
   ],
   "execution_count": 45
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "使用invoke",
   "id": "d31fba1ea379e303"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T03:41:35.433171Z",
     "start_time": "2025-10-22T03:41:35.425524Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 2.from_template定义提示词模版对象\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    \"Tell me a {adjective} joke about {content}.\"\n",
    ")\n",
    "# 3.默认使用f-string进行格式化（返回格式好的字符串）\n",
    "prompt = prompt_template.invoke({\"adjective\": \"funny\", \"content\": \"chickens\"})\n",
    "print(prompt)\n",
    "print(type(prompt))"
   ],
   "id": "5ab77c77647e2b1b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "text='Tell me a funny joke about chickens.'\n",
      "<class 'langchain_core.prompt_values.StringPromptValue'>\n"
     ]
    }
   ],
   "execution_count": 47
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T03:44:04.585576Z",
     "start_time": "2025-10-22T03:44:04.570914Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 2.使用初始化器进行实例化\n",
    "prompt = PromptTemplate(\n",
    "    input_variables=[\"adjective\", \"content\"],\n",
    "    template=\"Tell me a {adjective} joke about {content}\")\n",
    "# 3. PromptTemplate底层是RunnableSerializable接口 所以可以直接使用invoke()调用\n",
    "prompt.invoke({\"adjective\": \"funny\", \"content\": \"chickens\"})"
   ],
   "id": "760bbf42ebeb6e40",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "StringPromptValue(text='Tell me a funny joke about chickens')"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 48
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T03:45:35.394752Z",
     "start_time": "2025-10-22T03:45:35.378637Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 方式3：使用组合提示词\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "prompt_template = (\n",
    "        PromptTemplate.from_template(\"Tell me a joke about {topic}\")\n",
    "        + \", make it funny\"\n",
    "        + \" and in {language}\"\n",
    ")\n",
    "prompt = prompt_template.invoke({\"topic\": \"French\", \"language\": \"chinese\"})\n",
    "print(prompt)"
   ],
   "id": "4907958b5801d003",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "text='Tell me a joke about French, make it funny and in chinese'\n"
     ]
    }
   ],
   "execution_count": 50
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 5.Prompt结合与大模型",
   "id": "e78316e87a663bbf"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-22T03:55:36.147645Z",
     "start_time": "2025-10-22T03:54:35.575780Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "dotenv.load_dotenv()\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"DASHSCOPE_API_KEY\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"DASHSCOPE_BASE_URL\")\n",
    "# 初始化大模型\n",
    "chat_llm = ChatOpenAI(model=\"qwen-max\")\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\"\n",
    ")\n",
    "prompt = prompt_template.format(product=\"电脑\", aspect1=\"性能\", aspect2=\"电池\")\n",
    "# prompt1 = prompt_template.invoke({\"product\":\"手机\",\"aspect1\":\"拍照\",\"aspect2\":\"续航\"})\n",
    "prompt1 = prompt_template.invoke(input={\"product\":\"手机\",\"aspect1\":\"拍照\",\"aspect2\":\"续航\"})\n",
    "print(type(prompt))\n",
    "print(type(prompt1))\n",
    "response=chat_llm.invoke(prompt) #使用非对话模型调用\n",
    "response1=chat_llm.invoke(prompt1)  #使用对话模型调用\n",
    "print(response. content)\n",
    "print(response1. content)"
   ],
   "id": "76ffe82212c1035e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n",
      "<class 'langchain_core.prompt_values.StringPromptValue'>\n",
      "电脑作为日常生活中不可或缺的工具，其性能和电池寿命是用户非常关注的两个方面。下面我将从这两个角度出发，对电脑进行一个大致的优缺点评价。\n",
      "\n",
      "### 性能\n",
      "\n",
      "**优点：**\n",
      "\n",
      "1. **处理速度快**：现代电脑配备了高性能处理器（如Intel Core i系列、AMD Ryzen系列），能够快速处理大量数据，满足用户对于游戏、图形设计、视频编辑等高需求应用的需求。\n",
      "2. **多任务处理能力强**：通过增加内存容量（RAM）和使用更强大的CPU，电脑可以同时流畅运行多个应用程序，提高工作效率。\n",
      "3. **存储空间大且多样**：提供从几百GB到几TB不等的硬盘或固态硬盘(SSD)选项，以及云存储服务，让用户拥有足够的空间来保存文件和个人资料。\n",
      "\n",
      "**缺点：**\n",
      "\n",
      "1. **成本较高**：为了获得更好的性能体验，往往需要投入更多的资金购买高端硬件配置。\n",
      "2. **散热问题**：高性能意味着更高的功耗，这可能导致设备过热，影响使用寿命。因此，良好的散热系统非常重要。\n",
      "3. **维护更新频繁**：随着软件版本的不断升级，旧款电脑可能无法兼容最新版软件，需要定期更换硬件或重新安装操作系统。\n",
      "\n",
      "### 电池\n",
      "\n",
      "**优点：**\n",
      "\n",
      "1. **便携性**：笔记本电脑特别强调了这一点，长续航能力使得用户可以在没有电源插座的情况下长时间工作或娱乐。\n",
      "2. **节能技术进步**：近年来，各大厂商都在努力提高电池效率并减少能耗，比如采用更先进的电池材料和技术。\n",
      "\n",
      "**缺点：**\n",
      "\n",
      "1. **容量限制**：尽管技术有所进步，但电池容量始终有限，特别是在执行复杂任务时消耗更快。\n",
      "2. **老化问题**：随着时间推移，锂电池会逐渐失去部分容量，导致续航时间缩短。\n",
      "3. **充电时间**：虽然快充技术有所发展，但对于一些低功率适配器来说，充满电仍需较长时间。\n",
      "\n",
      "综上所述，选择适合自己需求的电脑时，应综合考虑其性能与电池表现，并根据个人预算做出合理决策。\n",
      "评价手机的优缺点时，特别是关于拍照和续航这两个方面，需要考虑多个因素。不过，请注意，不同品牌、型号的手机在这些方面的表现会有所不同。下面我将从一般的角度来谈谈手机在这两个关键特性上的常见优点与缺点。\n",
      "\n",
      "### 拍照\n",
      "\n",
      "**优点：**\n",
      "- **高像素摄像头**：现代智能手机通常配备有高像素数的主摄像头，能够捕捉到细节丰富的照片。\n",
      "- **多功能性**：许多手机支持多种拍摄模式（如夜景模式、人像模式等），以及视频录制功能（包括慢动作、4K分辨率等）。\n",
      "- **AI优化**：利用人工智能技术自动调整设置或后处理图像，以提高图片质量。\n",
      "- **多摄像头系统**：通过配备超广角镜头、长焦镜头等多种类型的摄像头，为用户提供更广泛的拍摄可能性。\n",
      "\n",
      "**缺点：**\n",
      "- **夜间拍摄效果不佳**：尽管有专门的夜景模式，但与专业相机相比，在低光条件下的成像质量仍有差距。\n",
      "- **变焦能力有限**：虽然有些手机提供了光学变焦功能，但对于远距离物体的清晰度还是不如专用望远镜或者高端单反相机。\n",
      "- **过度依赖软件算法**：为了追求“好看”的照片，有时会过分使用美颜等功能，导致最终结果可能过于人工化，失去自然感。\n",
      "\n",
      "### 续航\n",
      "\n",
      "**优点：**\n",
      "- **大容量电池**：随着技术进步，现在市场上有很多手机都配备了较大容量的电池，可以满足一天甚至更长时间的正常使用需求。\n",
      "- **快速充电技术**：许多新款手机支持快充技术，能在短时间内给手机补充大量电量。\n",
      "- **节能模式**：大多数手机都有节能模式选项，在电量不足时可以通过降低屏幕亮度、限制后台应用活动等方式延长使用时间。\n",
      "\n",
      "**缺点：**\n",
      "- **电池老化问题**：随着时间推移，锂电池性能会逐渐下降，这意味着即使不怎么使用手机，其待机时间也会缩短。\n",
      "- **充电速度受限于适配器**：虽然手机本身支持快充，但如果使用的充电器功率不够，则无法达到最快的充电效率。\n",
      "- **长时间使用对电池寿命的影响**：频繁地让手机处于高温状态（比如边玩大型游戏边充电）可能会加速电池老化过程。\n",
      "\n",
      "综上所述，选择适合自己需求的手机时，可以根据个人对于拍照质量和续航能力的具体要求来进行权衡。同时也要考虑到其他因素如价格、操作系统偏好等。希望这能帮助你更好地了解手机在这两方面的一些基本情况！\n"
     ]
    }
   ],
   "execution_count": 67
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
